package com.agile.leetcode.concurrent.threadlocal;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/25 15:28
 */
public class ThreadLocalPractice {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 普通类型绑定
        //Demo demo = new Demo();
        // threadLocal的线程变量绑定

        ThreadLocalContent demo = new ThreadLocalContent();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            int j = i;
            new Thread(() -> {
                try {
                    countDownLatch.await();
                    demo.setContent(Thread.currentThread().getName() + "_" + "demo" + "_" + j);
                    System.out.println("==============");
                    System.out.println(Thread.currentThread().getName() + "_" + demo.getContent());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            countDownLatch.countDown();
        }
        Thread.sleep(5 * 1000);
    }
}

class Demo {
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

class ThreadLocalContent {
    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public String getContent() {
        return threadLocal.get();
    }

    public void setContent(String content) {
        threadLocal.set(content);
    }

    public void remove() {
        threadLocal.remove();
    }
}
